package com.king.service;

import com.king.bean.msg.WxBaseMessage;
import com.king.config.GlobalConst;
import com.king.handler.WxMessageHandler;
import com.king.utils.CommonUtils;
import com.thoughtworks.xstream.XStream;

import java.util.Arrays;
import java.util.Map;

public class WxService {

    private static final String TOKEN = GlobalConst.getConfig("MP_TOKEN");

    /**
     * 验证签名
     * 通过检验signature对请求进行校验
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean CheckSignature(String signature, String timestamp, String nonce) {
        //1）将token、timestamp、nonce三个参数进行字典序排序
        String[] strs = new String[]{TOKEN, timestamp, nonce};
        Arrays.sort(strs);

        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder sb = new StringBuilder();
        sb.append(strs[0]).append(strs[1]).append(strs[2]);
        String mySignature = CommonUtils.sha1(sb.toString());

        // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        return mySignature.equalsIgnoreCase(signature);
    }

    /**
     * 处理所有消息和事件的回复
     *
     * @param requestMap
     * @return 返回xml格式数据包
     */
    public static String getResponse(Map<String, Object> requestMap) {
        WxBaseMessage baseMessage = WxMessageHandler.handleMessage(requestMap);
        if (baseMessage != null) {
            return ConvertMessageToXml(baseMessage);
        }

        return "success";
    }

    private static String ConvertMessageToXml(WxBaseMessage baseMessage) {
        XStream xs = new XStream();
        xs.processAnnotations(baseMessage.getClass());
        System.out.println("-->" + baseMessage.getClass());
        return xs.toXML(baseMessage);
    }
}
